package cn.tedu.coolshark.filter;

import cn.tedu.coolshark.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",urlPatterns = {"/insertProduct.html","/admin.html"})
public class MyFilter implements Filter {
    //当过滤器初始化的时候执行
    public void init(FilterConfig config) throws ServletException {
    }
    //当过滤器被销毁时被执行
    public void destroy() {
    }
    //当接收到请求时会执行此方法,需要在此方法进行判断,是否允许访问Controller或静态资源文件
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //讲ServletRequest和ServletResponse 两个父类转换成子类 Http
        HttpServletRequest st = (HttpServletRequest)request;
        HttpServletResponse se = (HttpServletResponse)response;
        //得到会话对象
        HttpSession session = st.getSession();
        User user = (User)session.getAttribute("user");
        if(user!=null){
            chain.doFilter(request, response);//放行  允许访问资源
        }else{
            //代表未登录
            se.sendRedirect("/login.html");
        }
        System.out.println("过滤器执行了!");

    }
}
